package websocket.socket;

import org.apache.log4j.Logger;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;

import websocket.constant.Status;
import websocket.pojo.Message;
import websocket.service.SocketMsgHandleService;
import websocket.service.impl.SocketMsgHandleImpl;
import websocket.util.CommonUtil;

/**
 * 处理客户端消息的socket实现类
 * 
 * @author zhc
 * 
 */
public class MyWebSocket implements OnTextMessage {
	private static final Logger logger = Logger.getLogger(MyWebSocket.class
			.getName());

	private org.eclipse.jetty.websocket.WebSocket.Connection conn;
	private Long uid = -1L;
	private SocketMsgHandleService service = null;// 消息处理的服务类

	/**
	 * 有客户关闭连接
	 */
	@Override
	public void onClose(int status, String msg) {
		logger.info("socket关闭连接:" + status + "," + msg + "," + this.uid);
		service.selectHandle(new Message(Status.SYS_OFFLINE, this.uid, 0L, "",
				"offline"));
	}

	/**
	 * 当有新的用户连接时
	 */
	@Override
	public void onOpen(org.eclipse.jetty.websocket.WebSocket.Connection conn) {
		this.conn = conn;
		this.conn.setMaxIdleTime(-1);
		logger.info("有新的用户连接服务器......" + this);
	}

	/**
	 * 当有客户发送信息时
	 */
	@Override
	public void onMessage(String mess) {
		if (service == null)
			service = new SocketMsgHandleImpl(this);
		logger.info("收到了消息：" + mess);
		Message msg = CommonUtil.resolveMessage(mess);
		service.selectHandle(msg);
	}

	public org.eclipse.jetty.websocket.WebSocket.Connection getConn() {
		return conn;
	}

	public Long getUid() {
		return uid;
	}

	public void setUid(Long uid) {
		this.uid = uid;
	}

}
